package langman.util.languagefile;

import langman.util.languagefile.commons.TranslationMode;
import langman.util.languagefile.writer.LanguageWriter;

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Objects;

@SuppressWarnings("IOResourceOpenedButNotSafelyClosed")
public class LanguageFileBuilder implements AutoCloseable {

    private final LanguageWriter languageWriter;
    private final BufferedWriter writer;
    private final ByteArrayOutputStream referenceFileStream;

    private String currentCategory;

    public LanguageFileBuilder() {
        referenceFileStream = new ByteArrayOutputStream();
        OutputStreamWriter out = new OutputStreamWriter(referenceFileStream);
        writer = new BufferedWriter(out);
        languageWriter = new LanguageWriter(writer);
    }

    public LanguageFileBuilder withTranslation(String category, String key, String value, TranslationMode translationMode) throws IOException {
        if (!Objects.equals(currentCategory, category)) {
            languageWriter.writeCategory(category);
            currentCategory = category;
        }
        languageWriter.writeTranslation(key, value, translationMode);
        return this;
    }

    public byte[] build() throws IOException {
        writer.flush();
        return referenceFileStream.toByteArray();
    }

    @Override
    public void close() throws Exception {
        writer.close();
        languageWriter.close();
    }
}
